package com.lee.carinforecord;

import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;

public class FileTools {
    public static long start = 0;
    public static String timeStr = "";

    public static void initRecord() {
        start = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        timeStr = sdf.format(new java.util.Date());
        Log.i("date", timeStr);
        try{
            String path = Environment.getExternalStorageDirectory().getPath();
            File sdCardDir = new File(path);
            File readFile = new File(sdCardDir, "tmp.txt");
            File saveFile = new File(sdCardDir, "history.txt");

            InputStream inStream = new FileInputStream(readFile);
            InputStreamReader inputReader = new InputStreamReader(inStream);
            BufferedReader buffReader = new BufferedReader(inputReader);
            String line = buffReader.readLine()+"\n";
            Log.i("info", line);
            inStream.close();

            FileOutputStream outStream = new FileOutputStream(saveFile, true);
            outStream.write(line.getBytes());
            outStream.close();
        }catch (IOException e){}
    }

    public static void saveInfo(String str) {
        if (start == 0) {
            initRecord();
        }
        try {
            String path = Environment.getExternalStorageDirectory().getPath();
            long t = System.currentTimeMillis();
            Log.i("sd-path", path);
            File sdCardDir = new File(path);
            File saveFile = new File(sdCardDir, "tmp.txt");

            FileOutputStream outStream = new FileOutputStream(saveFile, false);
            str = timeStr + "," + (t - start) / 1000 + "," + str;
            outStream.write(str.getBytes());
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getHistory() {
        String content = "";
        String line = "";
        String path = Environment.getExternalStorageDirectory().getPath();
        File sdCardDir = new File(path);
        File saveFile = new File(sdCardDir, "history.txt");

        try{
            InputStream inStream = new FileInputStream(saveFile);
            InputStreamReader inputReader = new InputStreamReader(inStream);
            BufferedReader buffReader = new BufferedReader(inputReader);
            while (( line = buffReader.readLine()) != null) {
                content += line + "\n";
            }
            inStream.close();
        }catch (IOException e){}

        return content;
    }
}
